angular.module('easego.controllers', ["easego.services",'ngCordova'])

.controller('AppCtrl', function($scope, $ionicModal, $timeout,$rootScope,
$cordovaDevice,$ionicPlatform,$cordovaToast,
$ionicPopup,$localstorage,appConfig, LogonService,RegisterService) {
  //显示Toast提示
  $ionicPlatform.ready(function() {
    $rootScope.showToast = function(text){
      if(window.cordova){
        $cordovaToast.show(text, 'long', 'center')
        .then(function(success) {
        // success
        }, function(error) {
        // error
        });
      }else{
        console.log("Show Toast:",text);
      }
    };
  });

  /** 用户登录 */
  $ionicModal.fromTemplateUrl('templates/logon.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.logonModal = modal;
  });

  $scope.logon = function() {
    $scope.logonData = {};
    $scope.logonModal.show();
  };

  $scope.doLogon = function(){

    LogonService.logon($scope.logonData.logonName,$scope.logonData.password)
    .then(
      function(successResult) {
        $rootScope.currentUser = successResult.data;
        $rootScope.currentUserId = successResult.data._id;
        $rootScope.currentUserLogonName = $scope.logonData.logonName;
        $rootScope.currentUserPassword = $scope.logonData.password;
        $localstorage.setObject('currentUserObj',successResult.data);
        $localstorage.set('currentUserId',successResult.data._id);
        $localstorage.set('currentUserLogonName',$scope.logonData.logonName);
        $localstorage.set('currentUserPassword',$scope.logonData.password);
        $scope.logonModal.hide();
      },
      function(failResult){
        if(failResult.status== 401){
          $ionicPopup.alert({title: "账户名或密码不正确"});
        }
      }
    );
  }
  $scope.closeLogon = function() {
    $scope.logonModal.hide();
  };

  /** 用户注册 */
  $scope.registerData = {};
  $ionicModal.fromTemplateUrl('templates/register.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.registerModal = modal;
  });

  $scope.register = function() {
    $scope.registerModal.show();
  };

  $scope.doRegister = function(){
    RegisterService.register($scope.registerData.logonName,$scope.registerData.password,
	  $scope.registerData.mobile,$scope.registerData.name,$scope.registerData.verifyCode)
    .then(
      function(successResult) {
        $rootScope.currentUser = successResult.data;
        $rootScope.currentUserId = successResult.data._id;
        $rootScope.currentUserLogonName = $scope.logonData.logonName;
        $rootScope.currentUserPassword = $scope.logonData.password;        
        $localstorage.setObject('currentUserObj',successResult.data);
        $localstorage.set('currentUserId',successResult.data._id);
        $scope.registerData = {};
        $scope.closeRegister();
      },
      function(failResult){
        if(failResult.status== 401){
          $ionicPopup.alert({title: "账户名或密码不正确"});
        }
      }
    );
  }
  $scope.closeRegister = function() {
    $scope.registerModal.hide();
  };
  $scope.getVerificationCode = function(){
    
    RegisterService.getVerificationCode($scope.registerData.mobile)
    .then(
      function(successResult) {
        $scope.registerData.verifyCode = successResult.data.verificationCode;
      }
    );
  };

  /** 用户协议 */
  $ionicModal.fromTemplateUrl('templates/agreement.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.agreementModal = modal;
  });

  $scope.showAgreement = function() {
    $scope.agreementModal.show();
  };
  $scope.closeAgreement = function() {
    $scope.agreementModal.hide();
  }; 
})

//旅友行踪首页-已发布的游记列表
.controller('ArticlesCtrl',function ArticlesCtrl(
$scope,$stateParams,$ionicHistory,ArticleService) {
  $scope.articleList = [];
  $scope.$on('$ionicView.enter', function(e) {
    $scope.pageNo = 0;
    $scope.moreDataCanBeLoaded = true;
    ArticleService.list()
    .then(function(data) {$scope.articleList =  data.data; });
  });
  $scope.loadMoreArticles = function(){//载入更多
    ArticleService.list($scope.pageNo+1)
    .then(function(data) {
      var articleListReturned = data.data;
      if(articleListReturned.length > 0)
      {
        $scope.pageNo = $scope.pageNo + 1;
        _.times(articleListReturned.length,function(index){
          if (_.findIndex($scope.articleList, {_id: articleListReturned[index]._id})<0){
            $scope.articleList = _.concat($scope.articleList,articleListReturned[index]);
          }
        });
        $scope.$broadcast('scroll.infiniteScrollComplete'); 
      }
      else{
        $scope.moreDataCanBeLoaded = false;
      }
    });
  };
  $scope.loadNew = function(){ //刷新获取新记录
    ArticleService.list(0)
    .then(function(data) {
      var articleListReturned = data.data;
      if(articleListReturned.length > 0)
      {
        _.times(articleListReturned.length,function(index){
          if (_.findIndex($scope.articleList, {_id: articleListReturned[index]._id})<0){
            $scope.articleList.unshift(articleListReturned[index]);
          }
        });
        $scope.$broadcast('scroll.refreshComplete'); 
      }
    });
  };
})

//单个游记详情
.controller('ArticleCtrl', function ArticleCtrl(
$scope,$stateParams,ArticleService){
  var map, marker;

  $scope.$on('$ionicView.enter', function(e) {
    ArticleService.query($stateParams.articleId)
    .then(function(data) {
      $scope.article =  data.data[0]; 

      map = new AMap.Map('map',{
        resizeEnable: false,
        zoom: 10,
        center: [$scope.article.geolocationSpot[1], $scope.article.geolocationSpot[0]]
      });
      marker = new AMap.Marker({
              position: [$scope.article.geolocationSpot[1], $scope.article.geolocationSpot[0]]
      });
      marker.setMap(map);

      var  _articleSectionsSortedByDate = _.orderBy($scope.article.sections,["date"],["asc"]);
      _articleSectionsSortedByDate = _.map(_articleSectionsSortedByDate,
        function(section){
          section.shortDate = section.date.substring(0,10);
          return section;
      });
      $scope.sectionGroups = _.groupBy(_articleSectionsSortedByDate,'shortDate');
    });
  });
  $scope.$on('$ionicView.leave',function(e) {
    map = null;
    marker = null;
  });
})

//单个游记片段
.controller('SectionCtrl', function SectionCtrl(
$scope,$rootScope,$stateParams,ArticleService){
  $scope.newComment = null;

  $scope.$on('$ionicView.enter', function(e) {
    ArticleService.query($stateParams.articleId)
    .then(function(data) {
      $scope.article =  data.data[0]; 
      $scope.section = _.find($scope.article.sections,{_id: $stateParams.sectionId});
      $scope.section.date = Date.parse($scope.section.date);
    });
  });

  $scope.addComment = function(){
    ArticleService.addComment($rootScope.currentUserLogonName, $rootScope.currentUserPassword, 
    $scope.article._id, $scope.section._id, $scope.newComment, $rootScope.currentUserId)
    .then(function(data) {
      $scope.article =  data.data; 
      $scope.section = _.find($scope.article.sections,{_id: $scope.section._id});
      $scope.section.date = Date.parse($scope.section.date);
      $scope.newComment = null;
    });
  };

  $scope.addLike = function(){
    ArticleService.addLike($rootScope.currentUserLogonName, $rootScope.currentUserPassword, 
    $scope.article._id, $scope.section._id, $rootScope.currentUserId)
    .then(function(data) {
      $scope.article =  data.data; 
      $scope.section = _.find($scope.article.sections,{_id: $scope.section._id});
      $scope.section.date = Date.parse($scope.section.date);
    });
  };

  $scope.alreadyLiked = function(){
    if(!$scope.section) return true; //还未load到数据
    if(!$scope.section.likes) return false;
    return _.includes(
      _.map($scope.section.likes,function(like){return like.liker._id;}),
      $rootScope.currentUserId);
  }
})

/** 创建游记Article */
.controller('ArticleNewCtrl', function ArticleNewCtrl($scope,$rootScope,$state,ArticleService){
  var map, marker, clickEventListener;

  $scope.$on('$ionicView.enter', function(e) {
    $scope.articleNewData = {};
    map = new AMap.Map('map-new-article',{
      resizeEnable: true,
      zoom: 10,
    });

    map.on('moveend', function(){
      setLocation(map);
    });
    clickEventListener = map.on('click', function(e) {
      //console.log(e.lnglat.getLng(),e.lnglat.getLat());
      if(marker) map.remove(marker);
      marker = new AMap.Marker({
        position: [e.lnglat.getLng(), e.lnglat.getLat()]
      });
      marker.setMap(map);
      $scope.articleNewData.geolocationSpot = [e.lnglat.getLng(),e.lnglat.getLat()];
      setLocation(map);
    });
  });

  $scope.$on('$ionicView.leave',function(e) {
    map = null;
    marker = null;
    clickEventListener = null;
  });

  var setLocation = function(mapObj){
    mapObj.getCity(function(data) {
      $scope.articleNewData.location = "中国,"+data.province+","+data.city;
    });
  };

  $scope.doArticleNew = function(){
    ArticleService.newArticle($rootScope.currentUserLogonName, $rootScope.currentUserPassword, 
    $scope.articleNewData.name, $scope.articleNewData.geolocationSpot,
    $scope.articleNewData.location,$rootScope.currentUserId)
    .then(function(data) {
      // console.log(data.data)
      $state.go("app.articles-show-author",{articleId: data.data._id, removeBackViewCount: 1});
    });
  };
})

.controller('ArticleAuthorCtrl', function ArticleAuthorCtrl(
$scope,$rootScope,$stateParams,$state,$ionicHistory,$ionicPlatform,
$cordovaImagePicker,$cordovaToast,$cordovaFileTransfer,$cordovaCamera,
ArticleService,appConfig){
  var map, marker;

  $scope.$on('$ionicView.enter', function(e) {
    if($stateParams.removeBackViewCount){
      _.times($stateParams.removeBackViewCount,function(){$ionicHistory.removeBackView();}); 
    }
    ArticleService.query($stateParams.articleId)
    .then(function(data) {
      $scope.article =  data.data[0]; 

      map = new AMap.Map('map-author',{
        resizeEnable: false,
        zoom: 10,
        center: [$scope.article.geolocationSpot[1], $scope.article.geolocationSpot[0]]
      });
      marker = new AMap.Marker({
              position: [$scope.article.geolocationSpot[1], $scope.article.geolocationSpot[0]]
      });
      marker.setMap(map);

      var  _articleSectionsSortedByDate = _.orderBy($scope.article.sections,["date"],["asc"]);
      _articleSectionsSortedByDate = _.map(_articleSectionsSortedByDate,
        function(section){
          section.shortDate = section.date.substring(0,10);
          return section;
      });
      $scope.sectionGroups = _.groupBy(_articleSectionsSortedByDate,'shortDate');
    });
  });

  $scope.$on('$ionicView.leave',function(e) {
    map = null;
    marker = null;
  });

  $ionicPlatform.ready(function() {
    //选择照片上传
    $scope.pickImage = function(element){
      $scope.$apply(function () {
        $scope.theFile = element.files[0];
        ArticleService.addArticleSectionImage(
          $rootScope.currentUserLogonName, $rootScope.currentUserPassword,
          $scope.article._id,$scope.theFile)
        .then(function(sectionId){
          $state.go("app.articles-section-show-author",
                  {articleId: $scope.article._id, sectionId: sectionId, removeBackViewCount: 0});
        },function(evt){
          console.log(evt);
        });
      });

    };
    //拍照上传
    $scope.takePicture= function(){
      if (!window.cordova) {
        console.log("No Cordova Installed!");
        return;
      }
      var options = {
        quality: 100,
        destinationType: Camera.DestinationType.DATA_URL,
        sourceType: Camera.PictureSourceType.CAMERA,
        allowEdit: true,
        encodingType: Camera.EncodingType.JPEG,
        targetWidth: 800,
        targetHeight: 600,
        popoverOptions: CameraPopoverOptions,
        saveToPhotoAlbum: false,
        correctOrientation:false
      };

      $cordovaCamera.getPicture(options).then(function(imageData) {
        ArticleService.addArticleSectionImageBase64(
          $rootScope.currentUserLogonName, $rootScope.currentUserPassword,
          $scope.article._id,imageData)
        .then(function(result){
          $state.go("app.articles-section-show-author",
                  {articleId: $scope.article._id, sectionId: result.data._id, removeBackViewCount: 0});
        },function(evt){
          console.log(evt);
        });

      }, function(err) {
        console.log(err);
      });
    };
  });  
})

.controller('SectionAuthorCtrl', function SectionAuthorCtrl(
$scope,$rootScope,$stateParams,$state,$ionicHistory,ArticleService){
   
  $scope.$on('$ionicView.enter', function (e) {
    if ($stateParams.removeBackViewCount) {
      _.times($stateParams.removeBackViewCount, function () { $ionicHistory.removeBackView(); });
    }
    ArticleService.query($stateParams.articleId)
      .then(function (data) {
        $scope.article = data.data[0];
        $scope.sectionData = _.find($scope.article.sections,{_id: $stateParams.sectionId});
        $scope.sectionData.date = new Date(Date.parse($scope.sectionData.date));
        $scope.sectionData.time = new Date(Date.parse($scope.sectionData.date));
        $scope.sectionData.isArticleCoverImage = 
          $scope.sectionData.imageFileName == $scope.article.coverImageFileName;
      })
  });

  $scope.doSectionUpdate = function () {
    $scope.sectionData.date.setHours($scope.sectionData.time.getHours());
    $scope.sectionData.date.setMinutes($scope.sectionData.time.getMinutes());
    ArticleService.updateSection($rootScope.currentUserLogonName, $rootScope.currentUserPassword, 
    $scope.article._id, $scope.sectionData._id, $scope.sectionData.text,$scope.sectionData.date,
    $scope.sectionData.imageFileName,$scope.sectionData.isArticleCoverImage)
    .then(function(data) {
      $ionicHistory.removeBackView();
      $state.go("app.articles-show-author",{articleId: data.data._id, removeBackViewCount: 1});
    });
  };
})

.controller('SettingCtrl',function SettingCtrl(
$scope,$rootScope,$ionicModal,$ionicHistory,$state,$localstorage,UserService){
  $scope.updateUserImage = function(element){
    $scope.$apply(function () {
      $scope.theFile = element.files[0];
      UserService.updateUserImage(
        $rootScope.currentUserLogonName, $rootScope.currentUserPassword,
        $rootScope.currentUserId, $scope.theFile)
      .then(function(user){
        $rootScope.currentUser = user;
        $localstorage.setObject('currentUserObj',user);
      },function(evt){
        console.log(evt);
      });
    });
  };

  /** 更改账户设置 */
  $ionicModal.fromTemplateUrl('templates/account-setting.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.userAccountModal = modal;
  });

  $scope.doAccountSetting = function(){
    $scope.userAccountData = {};
    _.assign($scope.userAccountData,$rootScope.currentUser);
    $scope.userAccountModal.show();
  };

  $scope.closeAccountSetting = function() {
    $scope.userAccountModal.hide();
  };
  $scope.confirmAccountSetting = function () {
    UserService.updateAccountSetting(
    $rootScope.currentUserLogonName, $rootScope.currentUserPassword,
    $rootScope.currentUserId, 
    $scope.userAccountData.name, $scope.userAccountData.mobile,
    $scope.userAccountData.email, $scope.userAccountData.gender,
    $scope.userAccountData.introduction)
    .then(function (result) {
      $rootScope.currentUser = result.data;
      $localstorage.setObject('currentUserObj',$rootScope.currentUser);
      $scope.userAccountModal.hide();
    });
  };

   /** 更改密码 */
  $ionicModal.fromTemplateUrl('templates/change-password.html', {
    scope: $scope
  }).then(function(modal) {
    $scope.changePasswordModal = modal;
  });

  $scope.doChangePassword = function(){
    $scope.passwordData = {};
    $scope.changePasswordModal.show();
  };

  $scope.closeChangePassword = function() {
    $scope.changePasswordModal.hide();
  };

  $scope.confirmChangePassword = function () {
    UserService.changePassword(
    $rootScope.currentUserLogonName, $scope.passwordData.oldPassword,
    $rootScope.currentUserId, $scope.passwordData.password1)
    .then(function (result) {
      $rootScope.currentUser = result.data;
      $localstorage.setObject('currentUserObj',$rootScope.currentUser);
      $rootScope.currentUserPassword = $scope.passwordData.password1;
      $localstorage.set('currentUserPassword',$rootScope.currentUserPassword);
      $scope.changePasswordModal.hide();
      $rootScope.showToast("密码已更改");
    });
  };
})

.controller('MyArticlesCtrl',function MyArticlesCtrl(
$scope,$rootScope,$ionicModal,$ionicHistory,$state,$localstorage,ArticleService){
  $scope.$on('$ionicView.enter', function(e) {
    ArticleService.listOfAuthor($rootScope.currentUserId)
    .then(function(data) {$scope.articleList =  data.data; });
  });
})

.controller('ArticleEditAuthorCtrl',function ArticleEditAuthorCtrl(
$scope,$rootScope,$ionicModal,$ionicHistory,$state,$stateParams,$localstorage,ArticleService){
  var map, marker;

  $scope.$on('$ionicView.enter', function(e) {
    ArticleService.query($stateParams.articleId)
    .then(function(data) {
      $scope.article =  data.data[0];
      $scope.article.startDate = new Date(Date.parse($scope.article.startDate));
      $scope.article.publishState = ($scope.article.state=="已发布");

      map = new AMap.Map('map-update-article',{
        resizeEnable: true,
        zoom: 10,
      });
      marker = new AMap.Marker({
        position: [$scope.article.geolocationSpot[1], $scope.article.geolocationSpot[0]]
      });
      marker.setMap(map);

      map.on('moveend', function(){
        setLocation(map);
      });
      var setLocation = function (mapObj) {
        mapObj.getCity(function (data) {
          $scope.article.location = "中国," + data.province + "," + data.city;
        });
      };
      var clickEventListener = map.on('click', function(e) {
        if(marker) map.remove(marker);
        marker = new AMap.Marker({
          position: [e.lnglat.getLng(), e.lnglat.getLat()]
        });
        marker.setMap(map);
        $scope.article.geolocationSpot = [e.lnglat.getLat(),e.lnglat.getLng()];
        setLocation(map);
      });
    });
  });

  $scope.$on('$ionicView.leave',function(e) {
    map = null;
    marker = null;
  });

  $scope.confirm = function(){ //确认编辑更改结果
    ArticleService.updateArticle(
    $rootScope.currentUserLogonName, $rootScope.currentUserPassword,
    $scope.article._id, $scope.article.name, $scope.article.geolocationSpot,
    $scope.article.location, $scope.article.startDate, $scope.article.mileage,
    $scope.article.publishState ? "已发布" : "编辑", $scope.article.publicity)
    .then(function(data) {
      $rootScope.showToast("游记"+ $scope.article.name +"已更改");
      $ionicHistory.goBack();
    });
  };
})

.controller('ProductsCtrl',function ProductsCtrl(
$scope,ProductService,productCategories){
  $scope.$on('$ionicView.enter', function(e) {
    ProductService.list()
    .then(function(result){
      $scope.productCategories = productCategories;
      $scope.productSuites = [
        {coverImageFileName: "classic-cover.jpg", suiteName: "经典",
        products: _.filter(result.data,{category: "classic"}), category:"classic"},
        {coverImageFileName: "honeymoon-cover.jpg", suiteName: "蜜月",
        products: _.filter(result.data,{category: "honeymoon"}), category:"honeymoon"},        
        {coverImageFileName: "kid-cover.jpg", suiteName: "亲子",
        products: _.filter(result.data,{category: "kid"}), category:"kid"},
        {coverImageFileName: "family-cover.jpg", suiteName: "家庭",
        products: _.filter(result.data,{category: "family"}), category:"family"},
      ];
    });
  });
})

.controller('ProductsCategoryCtrl',function ProductsCategoryCtrl(
$scope,$stateParams,ProductService,productCategories){
  $scope.$on('$ionicView.enter', function(e) {
    ProductService.list($stateParams.category)
    .then(function(result){
      $scope.categoryText = productCategories[$stateParams.category];
      $scope.productList = result.data;
    });
  });
})

.controller('ProductCtrl',function ProductCtrl(
$scope,$stateParams,ProductService){
  $scope.$on('$ionicView.enter', function(e) {
    ProductService.list()
    .then(function(result){
      $scope.product = _.find(result.data,{_id: $stateParams.productId});
    });
  });
})

.controller('PoCreateCtrl',function PoCreateCtrl(
$scope,$rootScope,$stateParams,$ionicHistory,ProductService,PoService){
  $scope.$on('$ionicView.enter', function(e) {
    $scope.poData={};
    ProductService.list()
    .then(function(result){
      $scope.poData.product = _.find(result.data,{_id: $stateParams.productId});
      $scope.poData.amount = 1;
    });
  });
  $scope.submit = function(){
    PoService.newPo($rootScope.currentUserLogonName, $rootScope.currentUserPassword,
    $stateParams.productId, $rootScope.currentUserId, $scope.poData.amount,
    $scope.poData.useDate, $scope.poData.contactName, $scope.poData.contactPhone,
    $scope.poData.contactEmail)
    .then(function(result){
      $rootScope.showToast("谢谢,您的订单已成功提交,我们的客服人员将尽快与您联系确认!");
      $ionicHistory.goBack();
    });
  };
})

.controller('PoListCtrl',function PoListCtrl($scope,$rootScope,PoService){
  $scope.$on('$ionicView.enter', function(e) {
    PoService.list($rootScope.currentUserLogonName, $rootScope.currentUserPassword,
    $rootScope.currentUserId)
    .then(function(result){
      $scope.pos = result.data;
    });
  });
})
;
